import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormDependency,
  ProFormDigit,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable
} from "@ant-design/pro-components";
import {Button, Col, Drawer, Form, Row, Space, Tooltip} from "antd";
import React, {useRef, useState} from "react";
import {EditOutlined, MoneyCollectOutlined, PlusOutlined, SearchOutlined, SettingFilled} from "@ant-design/icons";
import {history} from '@umijs/max';
import {globalApi, globalLoadTableApi, globalLoadTableApiCode, handleGloblApi} from "@/services/admin-api/globalApi";
import './index.css'
import dayjs from "dayjs";
import {citySelect} from "@/pages/Worker/Management";
import {Access, useAccess} from 'umi'

export type Order = {
  orderId: number;
  customerName: string;
  customerPhone: number;
  serviceTime: string;
  startAddress: string;
  startAddressLng: number;
  startAddressLat: number;
  newAddress: string;
  newAddressLng: number;
  newAddressLat: number;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
  orderStatus: number;
  dispatchStatus: boolean;
  distance: number
  handInTime: string
  handInUserId: number
  handInUserName: string
  writeOffTime: string
  writeOffUserId: number
  writeOffUserName: string
  storeId: number
  storeName: string
  productTotalPrice: number
  otherPrice: number
  discountsPrice: number
  totalPrice: number
  shouldDeposit: number
  payDeposit: number
  payFinalPayment: number
  productId: number
  productName: string
  cityCode: string
  cityName: string
  startFloor: number
  startElevator: boolean
  startFloorPrice: number
  newFloor: number
  newElevator: boolean
  newFloorPrice: number
  kmPrice: number
  customerRemark: string
  serviceRemark: string
  orderRemark: string
};

export const orderStatusSelect = [
  {label: '待确认', value: 0},
  {label: '待付定金', value: 1},
  {label: '已确认', value: 2},
  {label: '已完成', value: 3},
  {label: '取消', value: 4},
]

export const orderStatus: any = {
  0: {text: '待确认', status: 'Warning'},
  1: {text: '待付定金', status: 'Default'},
  2: {text: '已确认', status: 'Processing'},
  3: {text: '已完成', status: 'Success'},
  4: {text: '取消', status: 'Error'},
}

interface DescriptionItemProps {
  title: string;
  content: React.ReactNode;
}

export const DescriptionItem = ({title, content}: DescriptionItemProps) => (
  <div className="site-description-item-profile-wrapper">
    <p className="site-description-item-profile-p-label">{title}:</p>
    {content}
  </div>
);

const storeSelect = await globalApi('/store/select', {})

// const payType = [{label: '订单定金', value: 0}, {label: '订单尾款', value: 1}]
export const payType = await globalApi('/config/dict', {key: 'pay_type'})
// const paySource = [{label: '抖音券', value: 0}, {label: '微信支付', value: 1}]
export const paySource = await globalApi('/config/dict', {key: 'pay_source'})

export default () => {

  const access = useAccess()

  const actionRef = useRef<ActionType>();

  const [modalOpen, handleModalOpen] = useState(false);
  const [modalDouyinOpen, handleDouyinModalOpen] = useState(false);
  const [modalOrderDouyinOpen, handleOrderDouyinModalOpen] = useState(false);
  const [drawerOpen, handleDrawerOpen] = useState(false);
  const [form] = Form.useForm();
  const [formDouyin] = Form.useForm();
  const [formOrderDouyin] = Form.useForm();
  const [order, setOrder] = useState<Order>()

  const columns: ProColumns<Order>[] = [
    {title: '订单ID', dataIndex: 'orderId', valueType: 'text', copyable: true, width: 135},
    {title: '名称', dataIndex: 'customerName', valueType: 'text'},
    {title: '电话', dataIndex: 'customerPhone', valueType: 'text', copyable: true, width: 120},
    {
      title: '状态',
      dataIndex: 'orderStatus',
      valueType: 'select',
      valueEnum: orderStatus,
      fieldProps: {options: orderStatusSelect},
    },
    {
      title: '城市',
      dataIndex: 'cityCode',
      valueType: 'select',
      fieldProps: {options: citySelect.data},
      hideInTable: true,
    },
    {title: '时间', dataIndex: 'serviceTime', valueType: 'dateTime', hideInSearch: true,},
    {
      title: '服务时间', dataIndex: 'serviceTime', valueType: 'dateTimeRange', hideInTable: true, search: {
        transform: (value) => {
          return {serviceTimeStart: value[0], serviceTimeEnd: value[1],};
        },
      },
    },
    {title: '城市', dataIndex: 'cityName', valueType: 'text', hideInSearch: true,},
    {
      title: '店铺',
      dataIndex: 'storeId',
      valueType: 'select',
      fieldProps: {options: storeSelect.data, showSearch: true},
    },
    {title: '起点', dataIndex: 'startAddress', valueType: 'text', ellipsis: true},
    {title: '距离(km)', dataIndex: 'distance', valueType: 'digit', hideInSearch: true},
    {title: 'startAddressLng', dataIndex: 'startAddressLng', valueType: 'digit', hideInSearch: true,},
    {title: 'startAddressLat', dataIndex: 'startAddressLat', valueType: 'digit', hideInSearch: true,},
    {title: '新家', dataIndex: 'newAddress', valueType: 'text', ellipsis: true},
    {title: 'newAddressLng', dataIndex: 'newAddressLng', valueType: 'digit', hideInSearch: true,},
    {title: 'newAddressLat', dataIndex: 'newAddressLat', valueType: 'digit', hideInSearch: true,},
    {title: '套餐ID', dataIndex: 'productId', valueType: 'digit', hideInSearch: true},
    {title: '套餐', dataIndex: 'productName', valueType: 'text', hideInSearch: true},
    {title: '定金', dataIndex: 'payDeposit', valueType: 'money', hideInSearch: true},
    {title: '尾款', dataIndex: 'payFinalPayment', valueType: 'money', hideInSearch: true},
    {title: '总价', dataIndex: 'totalPrice', valueType: 'money', hideInSearch: true},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {
      title: '创建时间', dataIndex: 'createTime', valueType: 'dateTimeRange', hideInTable: true, search: {
        transform: (value) => {
          return {createTimeStart: value[0], createTimeEnd: value[1],};
        },
      },
    },
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      width: 130,
      render: (_, record) => [
        <Access accessible={access.canAuth('order:edit')}>
          <Tooltip key={'edit_' + record.orderId} title={"编辑订单"}><Button
            size="small" icon={<EditOutlined/>} type="primary"
            onClick={async () => {
              history.push(`/order/management/createOrUpdate?orderId=${record.orderId}`)
            }}
          /></Tooltip>
        </Access>,
        <Tooltip key={'editstatus_' + record.orderId} title="支付">
          <Button
            size="small" icon={<MoneyCollectOutlined/>} type="primary"
            onClick={async () => {
              form.setFieldsValue({...record})
              handleModalOpen(true)
            }}
          /></Tooltip>,
        <Tooltip key={'look_' + record.orderId} title="查看订单详情">
          <Button
            size="small" icon={<SearchOutlined/>} type="primary"
            onClick={async () => {
              handleDrawerOpen(true)
              setOrder({...record})
            }}
          /></Tooltip>,
      ],
      valueType: 'option',
    },
  ];

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<Order>
      columns={columns} actionRef={actionRef} search={{span: 4}} size={"small"}
      headerTitle={

        <Space>
          <Access accessible={access.canAuth('order:add')}>
            <Tooltip title={"新增订单"}>
              <Button type="primary" icon={<PlusOutlined/>} onClick={() => {
                history.push('/order/management/createOrUpdate')
              }}/>
            </Tooltip>
          </Access>
          {/*<Tooltip title={"抖音验券"}>*/}
          {/*  <Button*/}
          {/*    key="douyin" icon={<TikTokOutlined/>} type="primary" onClick={() => {*/}
          {/*    handleDouyinModalOpen(true)*/}
          {/*  }}/>*/}
          {/*</Tooltip>*/}
        </Space>
      }
      request={async (param) => globalLoadTableApiCode('/order/table', 'order:list:search', access, param)}
      rowKey={(record) => record.orderId}
      columnsState={{
        defaultValue: {
          productId: {show: false},
          startAddressLng: {show: false},
          startAddressLat: {show: false},
          newAddressLng: {show: false},
          newAddressLat: {show: false},
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false}
        }
      }}/>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalOrderDouyinOpen} onOpenChange={handleOrderDouyinModalOpen} form={formOrderDouyin}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/order/orderDouyinVerify', value)
        if (success) {
          actionRef.current?.reload();
          return true
        }
      }}
    >
      <ProFormDigit label="orderId" name="orderId" hidden/>

      <ProFormSelect label="支付方式" rules={[{required: true}]} name="payType" options={payType.data}/>
      <ProFormText
        label="抖音券码" name="douyinCode" rules={[{required: true}]} fieldProps={{autoComplete: 'new-password'}}/>

      <ProFormTextArea label="备注" name="payRemark"/>

    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalDouyinOpen} onOpenChange={handleDouyinModalOpen} form={formDouyin}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/order/douyinVerify', value)
        if (success) {
          actionRef.current?.reload();
          return true
        }
      }}
    >
      <ProFormText
        label="抖音券码" name="code" rules={[{required: true}]} fieldProps={{autoComplete: 'new-password'}}/>
      <ProFormText
        label="名称" name="customerName" rules={[{required: true}]} fieldProps={{autoComplete: 'new-password'}}/>
      <ProFormText
        label="电话" name="customerPhone" rules={[{required: true}]} fieldProps={{autoComplete: 'new-password'}}/>

      <ProFormSelect
        label="验券门店" rules={[{required: true}]} name="douyinPoiId" request={async (param) => {
        const r = await globalApi('/store/selectDoyin', param)
        return r.data
      }}/>

      <ProFormTextArea label="备注" name="remark"/>

    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/order/modifyStatus', value)
        if (success) {
          actionRef.current?.reload();
          return true
        }
      }}
    >
      <ProFormDigit label="orderId" name="orderId" hidden/>

      <ProFormSelect label="支付类型" name="paySource" options={paySource.data}/>
      <ProFormDependency name={['paySource']}>
        {({paySource}) => {
          if (paySource === 0) {
            return <ProFormText label="抖音券码" name="douyinCode"/>
          }
          return ''
        }}
      </ProFormDependency>
      <ProFormMoney label="支付金额" name="payMoney"/>
      <ProFormSelect label="支付方式" name="payType" options={payType.data}/>
      <ProFormSelect
        label="订单状态" rules={[{required: true}]} tooltip={"无需改变即可维持不变"} name="orderStatus"
        options={orderStatusSelect}/>
      <ProFormTextArea label="支付备注" name="payRemark"/>

    </ModalForm>

    <Drawer width={640} placement="right" closable={false} onClose={() => handleDrawerOpen(false)} open={drawerOpen}>
      <p className="site-description-item-profile-p" style={{marginBottom: 24}}>
        订单详情
      </p>
      <Row>
        <Col span={12}>
          <DescriptionItem title="订单ID" content={order?.orderId}/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="服务时间" content={dayjs(order?.serviceTime).format('YYYY-MM-DD HH:mm:ss')}/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="起点" content={order?.startAddress}/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="新家" content={order?.newAddress}/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="距离(km)" content={order?.distance}/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="店铺" content={order?.storeName}/>
        </Col>
      </Row>

      {/*<p className="site-description-item-profile-p" style={{marginBottom: 24}}>
        User Profile
      </p>
      <p className="site-description-item-profile-p">Personal</p>
      <Row>
        <Col span={12}>
          <DescriptionItem title="Full Name" content="Lily"/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="Account" content="AntDesign@example.com"/>
        </Col>
      </Row>
      <Row>
        <Col span={12}>
          <DescriptionItem title="City" content="HangZhou"/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="Country" content="China🇨🇳"/>
        </Col>
      </Row>
      <Row>
        <Col span={12}>
          <DescriptionItem title="Birthday" content="February 2,1900"/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="Website" content="-"/>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <DescriptionItem
            title="Message"
            content="Make things as simple as possible but no simpler."
          />
        </Col>
      </Row>
      <Divider/>
      <p className="site-description-item-profile-p">Company</p>
      <Row>
        <Col span={12}>
          <DescriptionItem title="Position" content="Programmer"/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="Responsibilities" content="Coding"/>
        </Col>
      </Row>
      <Row>
        <Col span={12}>
          <DescriptionItem title="Department" content="XTech"/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="Supervisor" content={<a>Lin</a>}/>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <DescriptionItem
            title="Skills"
            content="C / C + +, data structures, software engineering, operating systems, computer networks, databases, compiler theory, computer architecture, Microcomputer Principle and Interface Technology, Computer English, Java, ASP, etc."
          />
        </Col>
      </Row>
      <Divider/>
      <p className="site-description-item-profile-p">Contacts</p>
      <Row>
        <Col span={12}>
          <DescriptionItem title="Email" content="AntDesign@example.com"/>
        </Col>
        <Col span={12}>
          <DescriptionItem title="Phone Number" content="+86 181 0000 0000"/>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <DescriptionItem
            title="Github"
            content={
              <a href="http://github.com/ant-design/ant-design/">
                github.com/ant-design/ant-design/
              </a>
            }
          />
        </Col>
      </Row>*/}
    </Drawer>

  </PageContainer>
}
